package com.samsungmobile.common_module.SMS.Service;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

import com.ipx.www.api.services.smsapi51.types.SendResponse;
import com.pushmsg.ServiceMsgFormat;
import com.samsungmobile.common.ConfOta;
import com.samsungmobile.common.Logger;
import com.samsungmobile.common_module.Exception.CommonModuleException;
import com.samsungmobile.common_module.SMS.MessageBean;
import com.samsungmobile.common_module.SMS.RequestBean;
import com.samsungmobile.security.UKDESEncryptDecrypt;

public class Materna extends OtaService {

	public Materna() {
		this.serviceName = "materna";
		Logger.LOG_NOHUP.debug("=============Materna=====================");
	}
	
	@Override
	protected void setProperties(RequestBean rb, MessageBean mb) {
		
		String[] saCountry = ConfOta.getArray("countries");
		String sCountry = "";
		
		for ( int i=0; i < saCountry.length; i++){
			
			if( rb.getMsisdn().startsWith(saCountry[i]) ){
				sCountry = saCountry[i];
				break;
			}
		}

		String sCountryCode = ConfOta.getConf(sCountry+".code");
		mb.setCountryCode( sCountryCode );
		
		UKDESEncryptDecrypt ukdes = new UKDESEncryptDecrypt();
		
		mb.setId( ukdes.decrypt(ConfOta.getConf(sCountry+".id")) );
		mb.setPw( ukdes.decrypt(ConfOta.getConf(sCountry+".pw")) );
		
		if( !rb.getSmsType().equals("SMS") ){
			mb.setDcs(ConfOta.getInt(sCountry+"."+rb.getOperator()+".dcs"));
		}else{
			mb.setDcs(-1);
		}
		
		mb.setDa( rb.getMsisdn() ); 
	    mb.setOa( rb.getOriginatingAddress() );
	    
	    String sRegex = "^[0-9]+$";
	    //number type
	    if( rb.getOriginatingAddress().matches(sRegex))
	    	mb.setOt(0);
	    //alpha numeric
	    else
	    	mb.setOt(1);
	    
	    mb.setPhoneCode(ConfOta.getConf(sCountry + ".phoneCode") );
	}
	
	/**
	 * Sends a SMS to IPX and returns the IPX response
	 * @param mb
	 * @return
	 * @throws Exception
	 */
	protected SendResponse[] invoke(MessageBean mb) throws Exception {

		Logger.LOG_NOHUP.info("Materna.invoke(): Message count="+mb.getMessageCount());
		SendResponse[] soapResponse = new SendResponse[mb.getMessageCount()];

        try {
			
    		byte[] msg;
    		
            for( int i=0; i < mb.getMessageCount() ; i++ ){
    		
    			msg = setServiceMsgFormat(
    					mb.getBinaryMessage().get(i)
    					, mb.getDa()
    					, mb.getDa()
    					, mb.getCountryCode());
    			
    			soapResponse[i] = sendMsg(msg);
    			
    			if (soapResponse[i].getResponseCode() != 0) {
    				break;
    			}
            }
		}
		catch(Exception e) {
			Logger.LOG_NOHUP.error(e);
			return soapResponse;
		}

		return soapResponse;
	}

	@Override
	protected SendResponse[] sendText(RequestBean rb, MessageBean mb)
			throws Exception {
		throw new CommonModuleException( new String[]{"500", "API_INTERNAL_ERROR"} );

	}

	private byte[] setServiceMsgFormat( byte b[],
			String sender, String receiver, String country) {
		
		//sender = "00"+sender;
		receiver = "00"+receiver;
		String trid = "ge" + "80000000000001";

		ServiceMsgFormat smf = new ServiceMsgFormat(0);
		byte bTemp[] = null;
		try {
			smf.setEmsObject(null);
			smf.setDa(receiver);
			smf.setOa(sender);
			smf.setDataType(2);
			smf.setChargeType(1);
			smf.setUserData(null, b);
			smf.setUserId("free_gbr");
			smf.setMsgType(5);
			smf.setTrId(trid);
			smf.setMsgFmt(2);
			smf.setPointCode(0);
			smf.encode();
			bTemp = smf.getPacket();
		} catch (Exception e) {
			System.out.println("setServiceMsgFormat : " + e.toString());
		}
		return bTemp;
	}	
	
	private SendResponse sendMsg(byte[] b) throws IOException{
		Logger.LOG_NOHUP.debug("Materna.sendMsg()");
		SendResponse sendResponse = new SendResponse();
		sendResponse.setResponseCode(-1);
		Socket cSocket = null;
		BufferedOutputStream bos = null;
		
		try {
			cSocket = new Socket("smsd", 8888);
			bos = new BufferedOutputStream(cSocket.getOutputStream());
			bos.write(b, 0, b.length);
			bos.flush();
			bos.close();
			cSocket.close();
			sendResponse.setResponseCode(0);
			sendResponse.setResponseMessage("SUCCESS");
			Logger.LOG_NOHUP.debug("Materna: sendMsg was successful."+"( Host: "+cSocket.getRemoteSocketAddress()+")");
		} catch(ConnectException ce) {
			Logger.LOG_NOHUP.error(ce);
			sendResponse.setResponseCode(400);
			sendResponse.setResponseMessage(ce.getMessage());
			return sendResponse;
		} catch (Exception e) {
			Logger.LOG_NOHUP.error(e);
			sendResponse.setResponseCode(400);
			sendResponse.setResponseMessage(e.getMessage());
			return sendResponse;
		} finally {
			try {
				if(bos != null) {
					bos.close();
				}
				if(cSocket != null) {
					cSocket.close();
				}

			} catch (Exception e) {
				Logger.LOG_NOHUP.error(e);
			}
		}
		return sendResponse;
	}
	
}
